﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsForms
{
    public partial class EditForm : Form
    {
        public EditForm()
        {
            InitializeComponent();
        }

        private int id;

        public EditForm(int id, string title, string author, string creatTime)
        {
            InitializeComponent();

            this.id = id;
            txtTitle.Text = title;
            txtAuthor.Text = author;
            txtCreatedTime.Text = creatTime;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            var hasTitle = txtTitle.Text;
            var hasAuthor = txtAuthor.Text;
            var hasCreatTime = txtCreatedTime.Text;
            
            //更新
            if (id > 1)
            {
                if (!string.IsNullOrEmpty(hasTitle) && !string.IsNullOrEmpty(hasAuthor) && !string.IsNullOrEmpty(hasCreatTime))
                {
                    string update = string.Format("update Articles set Title = '{0}',Author = '{1}',CreatedTime = '{2}' where Id = '{3}'",hasTitle,hasAuthor,hasCreatTime,id);
                    var res = DbHelper.AddOrEditOrDeleSave(update);

                    if (res == 1)
                    {
                        MessageBox.Show("修改成功", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                }
            }
            //添加
            else
            {
                if (!string.IsNullOrEmpty(hasTitle) && !string.IsNullOrEmpty(hasAuthor) && !string.IsNullOrEmpty(hasCreatTime))
                {
                    string add = string.Format("insert into Articles(Title,Author,CreatedTime) values('{0}','{1}','{2}')", hasTitle, hasAuthor, hasCreatTime);
                    var res = DbHelper.AddOrEditOrDeleSave(add);

                    if (res == 1)
                    {
                        MessageBox.Show("保存成功", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                }
                else if(txtTitle.Text.ToString().Trim() == "")
                {
                    MessageBox.Show("文章名不得为空", "提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }
    }
}
